package net.embedded_projects.octopus.ui.views;

import net.embedded_projects.octopus.Octopus;
import net.embedded_projects.octopus.Octopus.GPIO;
import net.embedded_projects.octopus.ui.widgets.OctopusWidget;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.part.ViewPart;

public class GPIOView extends ViewPart {

	private Octopus octo;
	private GPIO gpio;
	
	private Display display;
	private Button[] gpioDir = new Button[44];
	
	private Thread gpioThread;
	private boolean doPolling;
	
	@Override
	public void createPartControl(Composite parent) {
		Composite container = new Composite(parent, SWT.NONE);
		container.setLayout(new GridLayout(2, false));
		
		final Button connect = new Button(container, SWT.TOGGLE);
		connect.setLayoutData(new GridData(SWT.CENTER, SWT.BEGINNING, true, false, 8, 1));
		connect.setText("Connect");
		connect.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				if(connect.getSelection())
					connect();
				else
					doPolling = false;
			}
		});
		display = connect.getDisplay();
		
		for(int i=0; i<21; i++) {
			gpioDir[i] = new Button(container, SWT.CHECK);
			gpioDir[i+23] = new Button(container, SWT.CHECK);
			gpioDir[i].setText("" + (i+1));
			gpioDir[i+23].setText("" + (i+24));
		}
		
		OctopusWidget octoWidget = new OctopusWidget(container, SWT.NO_BACKGROUND);
		octoWidget.setLayoutData(new GridData(266, 500));
	}
	
	private void connect() {
		
//		adcThread = new Thread(new Runnable() {
//			public void run() {
//				try {
//					octo = Activator.getDefault().getOctopus();
//					adc = octo.getADC();
//					adc.init(1);
//
//					doPolling = true;
//					while(doPolling) {
//						updateText("" + adc.get(1));
//						Thread.sleep(300);
//					}
//					octo.close();
//				} catch (Exception e) {
//					e.printStackTrace();
//				}
//			}
//		});
//		adcThread.start();		
	}

	private void updateText(final String str) {
		display.asyncExec(new Runnable() {
			public void run() {
//				adcText.setText(str);
			}
		});
	}
	
	@Override
	public void setFocus() {
		// TODO Auto-generated method stub

	}

}
